#include "ConvertDataType.h"
#include "string.h"
#include "stdio.h"


#ifdef __cplusplus
extern "C" {
#endif

/*************************************************
Function: 		hex2string
Description: 	hex字符数组转换成string字符串，用于printf显示等
Input: 			hex:原字符数组
                len:hex数组的长度
Output: 		ascII:输出的字符串
                newlen:输出的字符串长度
Return: 		
*************************************************/
void hex2string(char *hex,char *ascII,int len,int *newlen)
{
	int i = 0;
	char newchar[100] = {0};
	*newlen=len*3;
	for (i = 0; i< len; i++)
	{
		sprintf(newchar,"%02X ", hex[i]);
		strcat(ascII, newchar);
	}
}

/*************************************************
Function: 		string2hex
Description: 	字符串转换成hex,要求str只能是大写字母ABCDEF和数字
Input: 			str:要转换的字符串
Output: 		hex:转换后的hex字符数组
Return: 		0 成功
                1 不符合规则，失败
*************************************************/
#define ArrayLength 512
int string2hex(char* str,char* hex)
{
    int i = 0;
    int j = 0;
    unsigned char temp = 0;
    int str_len = 0;
    char str_cpy[ArrayLength] = {'0'};
    strcpy(str_cpy,str);
    str_len = strlen(str_cpy); 
    if(str_len==0)
    {
        return 1;
    }
    while(i < str_len)
    {
        if(str_cpy[i]>='0' && str_cpy[i]<='F') 
        {
            if((str_cpy[i]>='0' && str_cpy[i]<='9'))
            {
                temp = (str_cpy[i] & 0x0f)<<4;
            }
            else if(str_cpy[i]>='A' && str_cpy[i]<='F')
            {
                temp = ((str_cpy[i] + 0x09) & 0x0f)<<4;
            }
            else
            {
                return 1;
            }
        }
        else
        {
            return 1;
        }   
        i++;
        if(str_cpy[i]>='0' && str_cpy[i]<='F') 
        {
            if(str_cpy[i]>='0' && str_cpy[i]<='9')
            {
                temp |= (str_cpy[i] & 0x0f);
            }
            else if(str_cpy[i]>='A' && str_cpy[i]<='F')
            {
                temp |= ((str_cpy[i] + 0x09) & 0x0f);
            }
            else
            {
                return 1;
            }
        }
        else
        {
            return 1;
        } 
        i++;
        hex[j] = temp;
        // printf("%02x\n",temp);
        j++;
    }
    // printf("\n");
    return 0 ;
}

/**
  * @brief  打印数组
  * @param  str 数组地址 
  * @param  len 数组长度
  * @return none
  * @note   none
  */
void TRACE(unsigned char *str, unsigned int len)
{
    for (int i = 0; i < len; i++)
    {
        if ((i)%16==0)
            printf("\n");
        printf("%02x ",str[i]);
    }
    printf("\n\n");
}

// void main(void)
// {
//     char *input_sha256 = "80BCEDA048D16BCB4EE9A2F3DE0856EDC59F20C32C1FF4DBEA6EA18EE437826D";
//     int sha256_length = strlen(input_sha256);
//     char array_sha256[sha256_length];
//     string2hex(input_sha256,array_sha256);
// }

#ifdef __cplusplus
}
#endif
